// pages/my/BindPhone/BindPhone.js
Page({
  data:{
    userInfo:'',
    change:'',
    oldPhone:'',
    newPhone:'',
    phone:''
  },
  formatPhoneNumber(phone) {
    console.log('传入的手机号码:',phone);
    if (phone) {
        return phone.slice(0, 3) + '***' + phone.slice(7);
    }
    return '';
},
  oldPhone(e) {
    this.setData({
      oldPhone: e.detail.value
    });
  },
  newPhone(e) {
    this.setData({
      newPhone: e.detail.value
    });
  },
  changePhone(){
    this.setData({
      change:'false'
    })
  },
  changePhone2(){
    const {oldPhone,newPhone} = this.data
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (newPhone && !phoneRegex.test(newPhone)) {
        wx.showToast({
            title: '手机号格式不正确',
            icon: 'none'
        });
        return;
    }
    if (oldPhone!== this.data.userInfo.userPhone) {
      wx.showToast({
        title: '旧手机号和当前手机号不一致，请重新输入！',
        icon: 'none'
      });
      return;
    }
    wx.request({
      url: 'http://localhost:8080/user/edit',
      method: 'PUT',
      data:{
          userId:this.data.userInfo.userId,
          userPhone:newPhone
      },
      success: (res) => {
        if(res.data.code===1){
           // 更新本地缓存中的 userInfo
           let newUserInfo = {...this.data.userInfo};
           newUserInfo.userPhone = newPhone;
           wx.setStorage({
             key: 'userInfo',
             data: newUserInfo,
             success: () => {
               console.log('本地缓存更新成功');
             },
             fail: (err) => {
               console.error('本地缓存更新失败:', err);
             }
             });
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            success: () => {
                setTimeout(() => {
                    wx.reLaunch({
                        url: '/pages/my/my'
                    });
                }, 1000);
            }
        });
        }
    },
  },
 )},
 onLoad() {
  wx.getStorage({
      key: 'userInfo',
      success: (res) => {
          const userInfo = res.data;
          if (!userInfo) {
              wx.redirectTo({
                  url: '/pages/my/login/login'
              });
          } else {
              this.setData({
                userInfo:userInfo,
                phone:this.formatPhoneNumber(userInfo.userPhone)
              })
              // console.log(userInfo)
          }
      },
      fail: (err) => {
          if (err.errMsg === 'getStorage:fail data not found') {
              // 数据未找到，当作未登录处理，使用 wx.redirectTo 跳转到登录页面
              console.log("数据未找到");
              wx.redirectTo({
                  url: '/pages/my/login/login'
              });
          } else {
              // 其他错误，给出明确提示
              wx.showToast({
                  title: '获取本地存储信息出错，请稍后重试',
                  icon: 'none'
              });
              console.error('获取本地存储信息失败:', err);
          }
      }
  });
}
});